package com.seqb.manage.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.Constant;
import com.seqb.common.ScheduleJob;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.common.quartz.utils.QuartzManager;
import com.seqb.manage.task.dao.TaskDao;
import com.seqb.manage.task.domain.TaskDO;
import com.seqb.manage.task.service.TaskService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/15
 */
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskDao taskDao;

    @Autowired
    QuartzManager quartzManager;

    @Override
    public TaskDO get(Long id) {
        return taskDao.selectById(id);
    }

    @Override
    public Page<TaskDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, TaskDO.class);
        return (Page<TaskDO>) taskDao.selectList(queryWrapper);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, TaskDO.class);
        return taskDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(TaskDO task) {
        return taskDao.insert(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(TaskDO task) {
        try {
            TaskDO scheduleJob = get(task.getId());
            if (Constant.STATUS_RUNNING_STOP.equals(task.getJobStatus())) {
                quartzManager.deleteJob(QuartzManager.entityToData(scheduleJob));
            } else {
                if (!scheduleJob.getJobStatus().equals(task.getJobStatus())) {
                    scheduleJob.setJobStatus(ScheduleJob.STATUS_RUNNING);
                    quartzManager.addJob(QuartzManager.entityToData(scheduleJob));
                }
            }
            return taskDao.updateById(task);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(Long id) {
        try {
            TaskDO scheduleJob = get(id);
            quartzManager.deleteJob(QuartzManager.entityToData(scheduleJob));
            return taskDao.deleteById(id);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchRemove(Long[] ids) {
        for (Long id : ids) {
            try {
                TaskDO scheduleJob = get(id);
                quartzManager.deleteJob(QuartzManager.entityToData(scheduleJob));
            } catch (SchedulerException e) {
                e.printStackTrace();
                return 0;
            }
        }
        return taskDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public void initSchedule() {
        // 这里获取任务信息数据
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(new HashMap<>(16), TaskDO.class);
        List<TaskDO> jobList = taskDao.selectList(queryWrapper);
        for (TaskDO scheduleJob : jobList) {
            if ("1".equals(scheduleJob.getJobStatus())) {
                ScheduleJob job = QuartzManager.entityToData(scheduleJob);
                quartzManager.addJob(job);
            }
        }
    }

    @Override
    public void changeStatus(Long jobId, String cmd) {
        TaskDO scheduleJob = get(jobId);
        if (scheduleJob == null) {
            return;
        }
        if (Constant.STATUS_RUNNING_STOP.equals(cmd)) {
            scheduleJob.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
        } else {
            scheduleJob.setJobStatus(ScheduleJob.STATUS_RUNNING);
        }
        update(scheduleJob);
    }

    @Override
    public void updateCron(Long jobId) throws SchedulerException {
        TaskDO scheduleJob = get(jobId);
        if (scheduleJob == null) {
            return;
        }
        if (ScheduleJob.STATUS_RUNNING.equals(scheduleJob.getJobStatus())) {
            quartzManager.updateJobCron(QuartzManager.entityToData(scheduleJob));
        }
        update(scheduleJob);
    }

}
